/*
 * This file is part of Flicklib.
 *
 * Copyright (C) Francis De Brabandere
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.flicklib.service;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Map;
import org.apache.http.HttpResponse;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flicklib.tools.IOTools;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * Loads a http request
 * 
 * @author francisdb
 */
public class HttpSourceLoader implements SourceLoader {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpSourceLoader.class);
    private DefaultHttpClient client;
    private ProxyConfig proxyConfig;

    /**
     * Use HttpSourceLoader without proxy
     */
    public HttpSourceLoader() {
        client = new DefaultHttpClient();
    }

    /**
     * Use HttpSourceLoader with proxy
     * @param ProxyConfig Implementation
     */
    public HttpSourceLoader(ProxyConfig proxyConfig) {

        this();

        if (proxyConfig != null) {
            this.proxyConfig = proxyConfig;
            client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyConfig.getHttpHost());
            client.getCredentialsProvider().setCredentials(proxyConfig.getAuthScope(), proxyConfig.getCredentials());
        }

    }

    @Override
    public Source loadSource(String url) throws IOException {
        Source source = null;

        if (source == null) {

            source = load(url);

        }
        return source;
    }

    private Source load(String url) throws IOException {




        HttpGet httpGet = new HttpGet(url);


        Reader is = null;
        try {
            LOGGER.info("Loading " + url);
            HttpResponse response = client.execute(httpGet);
            String contentCharSet = EntityUtils.getContentCharSet(response.getEntity());

            if (contentCharSet != null) {

                is = new InputStreamReader(response.getEntity().getContent(), contentCharSet);
            } else {
                is = new InputStreamReader(response.getEntity().getContent());
            }
            String contentType = response.getEntity().getContentType().getValue();


            return new Source(httpGet.getURI().toString(), IOTools.readerToString(is), contentType);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ex) {
                    LOGGER.error("Could not close InputStream", is);
                }
            }
            if (httpGet != null) {
                httpGet.abort();

            }
        }
    }

    @Override
    public Source post(String url, Map<String, String> parameters, Map<String, String> headers) throws IOException {
        throw new RuntimeException("METHOD POST NOT IMPLEMENTET - returning NULL");
    }
}
